<template>
  <div class="home-page">
    <!-- 网站标题区域 -->
    <div class="hero-section">
      <div class="hero-content">
        <h1 class="site-title">
          <span class="title-text">一句话</span>
          <el-icon class="title-icon"><ChatDotRound /></el-icon>
          <span class="title-text">呈所想</span>
        </h1>
        <p class="site-subtitle">与 AI 对话轻松创建应用和网站</p>

        <!-- 用户提示词输入框 -->
        <div class="prompt-input-section">
          <el-input
            v-model="promptInput"
            type="textarea"
            :rows="3"
            placeholder="使用 NoCode 创建一个高效的小工具，帮我计算..."
            class="prompt-textarea"
            maxlength="500"
            show-word-limit
          />
          <div class="input-actions">
            <el-button class="upload-btn" :icon="Upload">上传</el-button>
            <el-button class="attach-btn" :icon="Paperclip">附件</el-button>
            <el-button
              type="primary"
              class="submit-btn"
              :icon="Position"
              @click="handleCreateApp"
              :loading="creating"
            >
              {{ creating ? '创建中...' : '创建应用' }}
            </el-button>
          </div>
        </div>

        <!-- 快捷标签 -->
        <div class="quick-tags">
          <el-tag
            v-for="tag in quickTags"
            :key="tag"
            class="quick-tag"
            @click="handleTagClick(tag)"
          >
            {{ tag }}
          </el-tag>
        </div>
      </div>
    </div>

    <!-- 我的作品区域 -->
    <div class="section my-apps-section">
      <div class="section-header">
        <h2 class="section-title">我的作品</h2>
        <el-button text type="primary" @click="viewAllMyApps">查看全部</el-button>
      </div>

      <div class="apps-grid" v-loading="loadingMyApps">
        <div
          v-for="app in myApps"
          :key="app.id"
          class="app-card"
          @click="handleAppClick(app)"
        >
          <div class="app-cover">
            <img v-if="app.cover" :src="app.cover" :alt="app.appName" />
            <div v-else class="default-cover">
              <el-icon><Document /></el-icon>
            </div>
          </div>
          <div class="app-info">
            <h3 class="app-name">{{ app.appName || '未命名应用' }}</h3>
            <p class="app-time">创建于 {{ formatTime(app.createTime) }}</p>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loadingMyApps && myApps.length === 0" class="empty-state">
          <el-empty description="暂无应用，快去创建一个吧！" />
        </div>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-if="myAppsTotal > 0"
        v-model:current-page="myAppsPage"
        v-model:page-size="pageSize"
        :total="myAppsTotal"
        layout="prev, pager, next"
        class="pagination"
        @current-change="loadMyApps"
      />
    </div>

    <!-- 精选案例区域 -->
    <div class="section featured-apps-section">
      <div class="section-header">
        <h2 class="section-title">精选案例</h2>
        <el-button text type="primary" @click="viewAllFeaturedApps">查看全部</el-button>
      </div>

      <div class="apps-grid" v-loading="loadingFeaturedApps">
        <div
          v-for="app in featuredApps"
          :key="app.id"
          class="app-card featured-card"
          @click="handleAppClick(app)"
        >
          <div class="app-cover">
            <img v-if="app.cover" :src="app.cover" :alt="app.appName" />
            <div v-else class="default-cover featured-default">
              <el-icon><Star /></el-icon>
            </div>
          </div>
          <div class="app-info">
            <h3 class="app-name">{{ app.appName || '精选应用' }}</h3>
            <div class="app-meta">
              <span class="app-author">{{ app.user?.userName || 'NoCode 官方' }}</span>
              <el-tag size="small" type="warning">精选</el-tag>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <el-pagination
        v-if="featuredAppsTotal > 0"
        v-model:current-page="featuredAppsPage"
        v-model:page-size="pageSize"
        :total="featuredAppsTotal"
        layout="prev, pager, next"
        class="pagination"
        @current-change="loadFeaturedApps"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import {
  ChatDotRound,
  Upload,
  Paperclip,
  Position,
  Document,
  Star
} from '@element-plus/icons-vue'
import api from '@/api'
import { useLoginUserStore } from '@/stores/loginUser'

const router = useRouter()
const loginUserStore = useLoginUserStore()

// 响应式数据
const promptInput = ref('')
const creating = ref(false)

// 我的应用
const myApps = ref<API.AppVO[]>([])
const loadingMyApps = ref(false)
const myAppsPage = ref(1)
const myAppsTotal = ref(0)

// 精选应用
const featuredApps = ref<API.AppVO[]>([])
const loadingFeaturedApps = ref(false)
const featuredAppsPage = ref(1)
const featuredAppsTotal = ref(0)

const pageSize = ref(8)

// 快捷标签
const quickTags = ref([
  '设置网页首页',
  '企业网站',
  '电商运营后台',
  '暗黑活动社区'
])

// 创建应用
const handleCreateApp = async () => {
  if (!promptInput.value.trim()) {
    ElMessage.warning('请输入应用描述')
    return
  }

  // 检查登录状态
  if (!loginUserStore.loginUser.userName || loginUserStore.loginUser.userName === '未登录') {
    ElMessage.warning('请先登录')
    router.push('/user/login')
    return
  }

  creating.value = true
  try {
    const result = await api.appController.addApp({
      initPrompt: promptInput.value.trim()
    })

    if (result.data.code === 0 && result.data.data) {
      ElMessage.success('应用创建成功')
      // 跳转到对话页面
      router.push({path:`/chat/${result.data.data}`, query: {autoStart: 'true'}})
    } else {
      ElMessage.error(result.data.message || '创建失败')
    }
  } catch (error) {
    console.error('创建应用失败:', error)
    ElMessage.error('创建失败，请重试')
  } finally {
    creating.value = false
  }
}

// 标签点击
const handleTagClick = (tag: string) => {
  promptInput.value = tag
}

// 应用卡片点击
const handleAppClick = (app: API.AppVO) => {
  router.push(`/chat/${app.id}`)
}

// 加载我的应用
const loadMyApps = async () => {
  // 检查登录状态
  if (!loginUserStore.loginUser.userName || loginUserStore.loginUser.userName === '未登录') {
    return
  }

  loadingMyApps.value = true
  try {
    const result = await api.appController.listMyAppVoByPage({
      pageNum: myAppsPage.value,
      pageSize: pageSize.value
    })

    if (result.data.code === 0 && result.data.data) {
      myApps.value = result.data.data.records || []
      myAppsTotal.value = result.data.data.totalRow || 0
    }
  } catch (error) {
    console.error('加载我的应用失败:', error)
  } finally {
    loadingMyApps.value = false
  }
}

// 加载精选应用
const loadFeaturedApps = async () => {
  loadingFeaturedApps.value = true
  try {
    const result = await api.appController.listGoodAppVoByPage({
      pageNum: featuredAppsPage.value,
      pageSize: pageSize.value,
      priority: 1
    })

    if (result.data.code === 0 && result.data.data) {
      featuredApps.value = result.data.data.records || []
      featuredAppsTotal.value = result.data.data.totalRow || 0
    }
  } catch (error) {
    console.error('加载精选应用失败:', error)
  } finally {
    loadingFeaturedApps.value = false
  }
}

// 查看全部
const viewAllMyApps = () => {
  router.push('/app/my')
}

const viewAllFeaturedApps = () => {
  router.push('/app/featured')
}

// 格式化时间
const formatTime = (time: string | undefined) => {
  if (!time) return ''
  return new Date(time).toLocaleDateString()
}

// 页面加载时获取数据
onMounted(() => {
  loadMyApps()
  loadFeaturedApps()
})
</script>

<style scoped>
.home-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 英雄区域 */
.hero-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  padding: 60px 40px;
  margin-bottom: 60px;
  text-align: center;
  color: white;
}

.site-title {
  font-size: 48px;
  font-weight: bold;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 12px;
}

.title-icon {
  font-size: 48px;
  color: #00d4aa;
}

.site-subtitle {
  font-size: 18px;
  margin-bottom: 40px;
  opacity: 0.9;
}

/* 输入区域 */
.prompt-input-section {
  max-width: 800px;
  margin: 0 auto 30px;
}

.prompt-textarea {
  margin-bottom: 16px;
}

.prompt-textarea :deep(.el-textarea__inner) {
  background: rgba(255, 255, 255, 0.95);
  border: none;
  border-radius: 12px;
  font-size: 16px;
  padding: 20px;
  resize: none;
}

.input-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.upload-btn, .attach-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
}

.upload-btn:hover, .attach-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}

.submit-btn {
  background: #00d4aa;
  border: none;
  padding: 0 30px;
}

.submit-btn:hover {
  background: #00b894;
}

/* 快捷标签 */
.quick-tags {
  display: flex;
  justify-content: center;
  gap: 12px;
  flex-wrap: wrap;
}

.quick-tag {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  cursor: pointer;
  transition: all 0.3s;
}

.quick-tag:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

/* 区域样式 */
.section {
  margin-bottom: 60px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.section-title {
  font-size: 28px;
  font-weight: bold;
  color: #2c3e50;
}

/* 应用网格 */
.apps-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 24px;
  margin-bottom: 30px;
}

.app-card {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s;
  cursor: pointer;
}

.app-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
}

.featured-card {
  border: 2px solid #f39c12;
}

.app-cover {
  height: 160px;
  overflow: hidden;
  position: relative;
}

.app-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-cover {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 48px;
}

.featured-default {
  background: linear-gradient(135deg, #fdcb6e 0%, #e17055 100%);
}

.app-info {
  padding: 20px;
}

.app-name {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.app-time {
  color: #7f8c8d;
  font-size: 14px;
}

.app-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.app-author {
  color: #7f8c8d;
  font-size: 14px;
}

/* 空状态 */
.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 60px 20px;
}

/* 分页 */
.pagination {
  display: flex;
  justify-content: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .hero-section {
    padding: 40px 20px;
  }

  .site-title {
    font-size: 32px;
    flex-direction: column;
    gap: 8px;
  }

  .title-icon {
    font-size: 32px;
  }

  .input-actions {
    flex-direction: column;
  }

  .quick-tags {
    gap: 8px;
  }

  .apps-grid {
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 16px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
}
</style>
